<template>
    <div class="sqbc">
        <template v-if="msg">
            <h5 style="">{{msg}}</h5>
            <RouterLink :to="{ name: 'Index' }">重新授权</RouterLink>
        </template>
        <!-- <div v-if="hhhh.data ">userid:{{ hhhh.data.userid }}</div>
       <div v-if="hhhh.data ">data:{{ hhhh }}</div> 
       <van-button type="danger" @click="clearCookies">清除缓存</van-button>
       <van-button type="danger" @click="login">登录</van-button>
       <p>[UserInfo]:{{ppppp}}</p> -->
       <h1>{{mm}}</h1>
    </div>
</template>
<script setup>
import {ref,onMounted} from "vue"
import{useRouter} from "vue-router"
import { loading,clearToast } from '@/utils/vant';
import{getAuthUserInfo,getMemberInfo} from '@/api/qy-wechat-api'
import { useUserStore } from '@/stores/modules/user'
import Cookies from "@/utils/auth.js"

const router = useRouter()
const userStore = useUserStore()

const msg = ref("")
const hhhh = ref({})
const ppppp = ref({})
const mm = ref(0)

onMounted(async ()=>{
    loading('正在授权中...')
    // 通过code换取网页授权access_token,获取企业微信成员id等信息
    const code= router.currentRoute.value.query.code
    const state= decodeURIComponent(router.currentRoute.value.query.state)
    const res = await getAuthUserInfo({code})
    hhhh.value = res
    mm.value=1
    if(res.code == 200){
        mm.value=2
        // 缓存用户userid
        if(res.data.userid){
            mm.value=3
            getMemberInfo({userId:res.data.userid}) // 数据库获取成员信息
            .then(res =>{
                ppppp.value = res
                mm.value=4
                if(res.code == 200 && res.data){
                    mm.value=5
                    userStore.setUserInfo(res.data)
                }else{
                    mm.value=6
                    msg.value = '获取成员信息出错！'
                    return
                }
                mm.value=7
                //userStore.set_qy_userid(res.data.userid)
                router.push(decodeURIComponent(state))
            })
            
        }else{
            msg.value = 'get userid error'
        }
        mm.value=8
        clearToast()
        
    }else{
        mm.value=9
        clearToast()
        msg.value = res.message
    } 
})

const clearCookies = ()=>{
    Cookies.remove('userInfo')
    router.push({name:'Login'})
}
// const login = async ()=>{
//     mm.value=10
//     await getMemberInfo({userId:hhhh.value.data.userid}) // 数据库获取成员信息
//     mm.value=11
//     router.push(decodeURIComponent(state))
// }
</script>

<style lang="scss" scoped>
    .sqbc{
        padding: 50px 20px;
        text-align: center;
        h5{
            text-align: center;
            font-size: 28px;
            margin: 0 0 30px 0;
        }
        a{
            display: inline-block;
            font-size: 26px;
            color: #67c23a;
        }
    }
</style>